package com.imonsoft.sqm.web.excel.IpicTargetExcel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.imonsoft.common.constant.CCommon;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.util.AjaxUtil;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.common.util.ValidatorUtil;
import com.imonsoft.sqm.service.basedata.IpicTargetService;
import com.imonsoft.sqm.service.excel.BaseExcel.ExcelService;
import com.imonsoft.sqm.service.excel.IpicTargetExcel.IpicTargetExcelService;

@Controller
@RequestMapping("/excel/ipicTargetExcel")
public class IpicTargetExcelController {
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private ExcelService excelService;
	@Autowired
	private IpicTargetExcelService ipicTargetExcelService;
	@Autowired
	private IpicTargetService ipicTargetService;

	@RequestMapping(value = "/ipicTargetImportUI.do")
	public void ipicTargetImportUI(ModelMap model) {
	}

	/**
	 * description Excel模版下载 on 2013-5-30
	 * 
	 * @a uthor zhouwei
	 */
	@RequestMapping(value = "/excelModel.do", method = RequestMethod.POST)
	public void excelModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		excelService.loadExcelModel(request, response, ConstantSqm.EXCEL_IPICTARGET);
	}

	/**
	 * description Excel导入操作 on 2013-5-14
	 * 
	 * @author zhouwei
	 */
	@RequestMapping(value = "/excelUpload.do", method = RequestMethod.POST)
	public void excelUpload(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {
		int maxSize = 200;
		int startRow = 1;
		ReturnMessage message = new ReturnMessage();
		String result = "<script type=\"text/javascript\">" + "window.parent.OnUploadCompleted('#reslut#');</script>";
		List<Object[]> contentList = null;
		try {
			contentList = excelService.readExcel(file.getInputStream(), maxSize, startRow);
			Map<String, Object> map = new HashMap<String, Object>();
			List<IpicTargetImportDto> importList = new ArrayList<IpicTargetImportDto>();
			List<IpicTargetImportDto> footerRow = new ArrayList<IpicTargetImportDto>();
			IpicTargetImportDto footer = new IpicTargetImportDto();
			List<IpicTargetImportDto> errorImportList = new ArrayList<IpicTargetImportDto>();
			List<IpicTargetImportDto> repeat=new ArrayList<IpicTargetImportDto>();
			List<String> errors = new ArrayList<String>();
			for (Object[] items : contentList) {
				IpicTargetImportDto dto = new IpicTargetImportDto();
				dto.setRow(Integer.parseInt(StringUtil.fixup(items[0])));
				dto.setSupplierCode((String) items[1]);
				dto.setYear((String) items[2]);
				if(ValidatorUtil.isDecimalLow(StringUtil.fixup(items[3]))){
					dto.setValue(Double.parseDouble(StringUtil.fixup(items[3])));
				}else{
					dto.setValue(0d);
				}
				repeat.add(dto);
				List<String> messages = ipicTargetExcelService.txCheckData(dto, repeat);
				dto.setHasError(messages.size() > 0);
				importList.add(dto);
				if (dto.isHasError()) {
					errorImportList.add(dto);
				}
				if (errorImportList.size() > maxSize) {
					break;
				}
				errors.addAll(messages);
			}
			footer.setRow(contentList.size());
			footerRow.add(footer);
			map.put("footer", footerRow);
			if (0 == errors.size()) {
				request.getSession().setAttribute(ConstantSqm.IPICTARGET_EXCEL_IMPORT, importList);
			}
			if (contentList.size() <= maxSize) {
				map.put("details", importList);
				if (errors.size() == 0) {
					message.setMsg("数据检查成功。");
				} else {
					map.put("errors", errors);
					message.setMsg("数据检查失败，请查看错误信息。");
				}
			} else {
				if (errors.size() == 0) {
					map.put("details", importList.subList(0, maxSize));
					message.setMsg("数据检查成功，列表中仅显示前500行，更多数据请查看Excel文件。");
				} else {
					if (errorImportList.size() > maxSize) {
						map.put("details", errorImportList.subList(0, errorImportList.size() - 1));
						map.put("errors", errors);
						message.setMsg("数据检查失败，由于错误数据太多，列表中仅显示前500行错误，请仔细检查Excel文件。");
					} else {
						map.put("details", errorImportList);
						map.put("errors", errors);
						message.setMsg("数据检查失败，由于数据量太大，列表中仅显示错误行。");
					}
				}
			}
			message.setObj(map);
			message.setSuccess(true);
		} catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderHTML(response, result.replaceFirst("#reslut#", JsonUtil.bean2json(message)));
	}
	/**
	 * 保存方法
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/ajaxSave.do", method = RequestMethod.POST)
	public void ajaxSave(HttpServletRequest request, HttpServletResponse response) {
		ReturnMessage message = new ReturnMessage();
		try {
			@SuppressWarnings("unchecked")
			List<IpicTargetImportDto> importList = (List<IpicTargetImportDto>) request.getSession().getAttribute(ConstantSqm.IPICTARGET_EXCEL_IMPORT);
			ipicTargetService.txInsertForSys(importList);
			request.getSession().removeAttribute(ConstantSqm.IPICTARGET_EXCEL_IMPORT);
			message.setSuccess(true);
		}  catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
	}
}
